<template>
  <div v-loading="loading" class="page-wrapper">
    <c-card title="权限列表" class="role-list">
      <el-button slot="func" size="small" type="primary" class="item" @click="showAddDlg">添加</el-button>
      <div class="row">
        <c-search
          v-model="searchText"
          :height="30"
          :width="200"
          placeholder="名称搜索"
          class="item"
          @submit="_getPrivilege"
        />
      </div>
      <el-table ref="table" :data="privilegeList" stripe style="width: 100%" height="498">
        <el-table-column prop="rightname" label="权限名称"></el-table-column>
        <el-table-column prop="rightcode" label="权限编码"></el-table-column>
        <el-table-column prop="memo" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="150">
          <template v-slot="{row}">
            <el-button size="small" type="text" @click="showEditDlg(row)">编辑</el-button>
            <el-button size="small" type="text" @click="deletePrivilege(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :page-size="page.size"
          :current-page.sync="page.index"
          :total="page.total"
          @current-change="_getPrivilege"
        ></el-pagination>
      </div>
    </c-card>
    <c-dlg :title="(privilege.rightid ? '编辑' : '添加') + '权限'" :visible.sync="dialogVisible">
      <el-form
        ref="form"
        :model="privilege"
        :rules="rules"
        label-width="60px"
        class="demo-ruleForm"
        label-position="top"
      >
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="权限名称" prop="rightname">
              <el-input v-model="privilege.rightname" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="权限编码" prop="rightcode">
              <el-input v-model="privilege.rightcode" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item" style="flex: 1">
            <el-form-item label="备注" prop="memo">
              <el-input v-model="privilege.memo" type="textarea" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <card-box title="已有资源列表">
        <el-button slot="func" size="mini" @click="showAddSourceDlg">添加资源</el-button>
        <div>
          <el-table :data="selectResources" style="width: 100%">
            <el-table-column prop="code" label="编号" show-overflow-tooltip></el-table-column>
            <el-table-column prop="name" label="名称" show-overflow-tooltip></el-table-column>
            <!-- <el-table-column prop="mrType" label="类型" show-overflow-tooltip></el-table-column> -->
            <el-table-column prop="path" label="路径" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作">
              <template v-slot="{row}">
                <el-button size="small" type="text" @click="deleteSelectRes(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </card-box>

      <div slot="footer">
        <el-button type="danger" size="small" @click="submitForm">提交</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </c-dlg>
    <select-resource
      :visible.sync="sourceDlgVisible"
      :select-rows="selectResources"
      @submit="selectSubmit"
      @cancle="selectSubmit"
    ></select-resource>
  </div>
</template>

<script>
import CCard from "@/components/CCard";
import CDlg from "@/components/CDlg";
import CardBox from "@/components/CardBox";
import CSearch from "@/components/CSearch";
import { clone } from "lodash";
import SelectResource from "./components/SelectResource";
import { queryRightRes, editRights, giveRes } from "@/api/user";
import { calcPageNum } from "@/utils";
export default {
  name: "Privilege",
  components: {
    CCard,
    CDlg,
    CSearch,
    SelectResource,
    CardBox
  },
  data() {
    return {
      loading: false,
      privilegeList: [],
      page: {
        index: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false,
      sourceDlgVisible: false,
      privilege: {},
      selectResources: [], // 已有资源列表
      resouceList: [{ pkid: 1, name: "hehe" }], // 资源列表
      searchText: "",
      curPriId: null,
      rules: {
        rightcode: [
          { required: true, message: "请输入权限编码", trigger: "blur" }
        ],
        rightname: [
          { required: true, message: "请输入权限名称", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    const h = this.$refs["table"].$el.clientHeight;
    const n = calcPageNum(h);
    this.$set(this.page, "size", n);
    this._getPrivilege();
  },
  methods: {
    _getPrivilege() {
      const params = {
        rightName: this.searchText,
        rows: this.page.size,
        page: this.page.index
      };
      this.loading = true;
      return this.$axios
        .get("plat/user/queryRights", { params })
        .then(res => {
          if (res.code === 1) {
            this.privilegeList = res.data.rows;
            this.$set(this.page, "total", res.data.total);
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e))
        .finally(() => (this.loading = false));
    },
    showAddDlg() {
      this.dialogVisible = true;
      if (this.privilege.rightid) {
        this.privilege = {};
        this.selectResources = [];
      }
    },
    showEditDlg(p) {
      if (p.rightid !== this.curPriId) {
        this.privilege = clone(p);
        this.curPriId = p.rightid;
        queryRightRes(p.rightid).then(data => {
          this.selectResources = data[0] && data[0].res;
        });
      }
      this.dialogVisible = true;
    },
    showAddSourceDlg() {
      if (!this.resouceList) {
        this.getResources();
      }
      this.sourceDlgVisible = true;
    },
    deletePrivilege(row) {
      this.$confirm("删除后不可恢复，确定删除吗？", "提示").then(() => {
        return this.$axios
          .delete("/plat/user/deleteRights", {
            params: { rightIds: row.rightid }
          })
          .then(res => {
            if (res.code === 1) {
              this._getPrivilege();
            } else {
              throw res.msg;
            }
          })
          .catch(e => this.$message.error(e.msg));
      });
    },
    deleteSelectRes(r) {
      this.selectResources = this.selectResources.filter(
        e => e.pkid !== r.pkid
      );
    },
    selectSubmit(list) {
      this.selectResources = list;
    },
    submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          const load = this.$loading();
          try {
            const data = await editRights(this.privilege);
            this._getPrivilege();
            await giveRes(data.rightid, this.selectResources.map(e => e.pkid));
            this.dialogVisible = false;
            load.close();
          } catch (e) {
            load.close();
            this.$message.error(e);
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.role-list {
  text-align: left;
}
/deep/ .el-table {
  .cell {
    color: #333;
  }
  .el-table__empty-block {
    min-height: 40px;
  }
  .el-table__empty-text {
    line-height: 40px;
  }
}
/deep/ .com-card-box main {
  padding: 0;
  th {
    height: 34px;
    line-height: 34px;
    background: #fff;
    padding: 0;
  }
  td {
    height: 32px;
    line-height: 32px;
    padding: 0;
  }
}
</style>
